<template>
  <el-dialog v-model="visible" title="填写拒绝理由" style="width: 30%;">
    <el-form :model="form" label-width="70px">
      <el-form-item label="拒绝理由">
        <el-input type="textarea" v-model="form.reason"></el-input>
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          ref="upload"
          action="#"
          list-type="picture-card"
          :file-list="fileList"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-preview="handlePreview"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dialogImageUrl" alt="预览图片" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit(file.id)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { AdminDetermine } from '../../api/announcement';

const visible = ref(false);
const form = reactive({
  reason: '',
  file: null,
});
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const upload = ref(null);
const file = ref([])
const emit = defineEmits(["refreshChild"])

// 打开对话框
const openDialog = (files) => {
    console.log("openDialog-files:" + files)
    file.value = files;
    console.log(file.value);
    visible.value = true;
};

// 关闭对话框
const closeDialog = () => {
  visible.value = false;
  form.reason = '';
  form.file = null;
  fileList.value = [];
};

// 文件选择改变时触发
const handleChange = (file, fileList) => {
    console.log("handleChange")
    const isValid = beforeUpload(file.raw);

    if (isValid && file.raw) {
        const reader = new FileReader();
        reader.onload = (e) => {
        dialogImageUrl.value = e.target.result;
        };
        reader.readAsDataURL(file.raw);
        form.file = file.raw;
    } else {
        // 如果验证失败，移除文件
        fileList.value = fileList.filter(f => f !== file);
    }

    // 如果有文件，则清空之前的文件列表，只保留当前文件
    if (fileList.length > 0) {
        fileList.value = [file];
    }
};

// 移除文件时触发
const handleRemove = (file, fileList) => {
  form.file = null;
  dialogImageUrl.value = '';
};

// 当超过文件数量限制时触发
const handleExceed = (files, fileList) => {
  ElMessage.warning('只能选择一张图片');
  // 清空之前的选择
  fileList.value = [];
  // 添加新选择的文件
  upload.value.clearFiles();
  const file = files[0];
  if (file) {
    fileList.value.push(file);
    handleChange(file, fileList.value);
  }
};

// 上传前检查
const beforeUpload = (file) => {
    console.log("handleChange")
    const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        ElMessage.error('上传的文件必须是图片格式 (JPG, PNG, GIF)');
    }
    if (!isLt2M) {
        ElMessage.error('上传的图片大小不能超过 2MB');
    }

    return isImage && isLt2M;
};

// 预览图片时触发
const handlePreview = (file) => {
  dialogImageUrl.value = file.url || URL.createObjectURL(file.raw);
  dialogVisible.value = true;
  // 点击预览图片时重新选择文件
  setTimeout(() => {
    upload.value.$refs.input.click(); // 触发文件选择器
  }, 0);
};

// 提交表单
const submit = async (id) => {
    try{
        // 在这里处理提交逻辑，比如发送给服务器等
        console.log('提交的数据:', form);
        const fd = new FormData();
        console.log("file.id:" + id);
        fd.append("ApplicationId", id);
        fd.append("isPass", false);
        if (form.reason != null){
            fd.append("reason", form.reason);
        }
        if (form.file != null){
            fd.append("file", form.file);
        }
        await AdminDetermine(fd);
        ElMessage.success("认定成功")
        closeDialog();
        emit("refreshChild")

    }
    catch(error){
        ElMessage.error("认定失败");
    }
}

// 暴露方法
defineExpose({ openDialog });
</script>

<style scoped>
/* 根据需要添加样式 */
</style>